<template>
  <el-button
    v-if="!isFullWindow"
    :title="$t('pageKvm.brandTitle.screenFull')"
    :icon="FullScreen"
    @click.stop="click"
  />
  <el-button
    v-else
    :title="$t('pageKvm.brandTitle.exitScreenFull')"
    :icon="FullScreen"
    @click.stop="click"
  />
</template>

<script setup lang="ts">
import { FullScreen } from '@element-plus/icons-vue';
import screenfull, { type Screenfull } from 'screenfull';
import { useI18n } from 'vue-i18n';

const i18n = useI18n();

const setIsFullWindow = inject('setIsFullWindow', (param1: boolean) => param1);
const props = defineProps<{ element: HTMLDivElement; isFullWindow: boolean }>();

onMounted(() => {
  init();
});

onBeforeUnmount(() => {
  destroy();
});

const click = () => {
  if (!(screenfull as Screenfull).enabled) {
    ElNotification({
      type: 'error',
      message: i18n.t('global.toast.browserNotSupport'),
    });
    return false;
  }
  (screenfull as Screenfull).on('error', (event) => {
    console.error('Failed to enable fullscreen', event);
  });
  if (!(screenfull as Screenfull).isFullscreen) {
    if (props.element) {
      (screenfull as Screenfull).request(props.element);
    } else {
      (screenfull as Screenfull).request();
    }
  } else {
    (screenfull as Screenfull).exit();
    if (!props.isFullWindow) {
      if (props.element) {
        setTimeout(() => {
          (screenfull as Screenfull).request(props.element);
        }, 50);
      } else {
        setTimeout(() => {
          (screenfull as Screenfull).request();
        }, 50);
      }
    }
  }
};

const change = () => {
  if ((screenfull as Screenfull).isFullscreen) {
    if (
      props.element == (screenfull as Screenfull).element ||
      (!props.element && (screenfull as Screenfull).element!.tagName == 'HTML')
    ) {
      if (setIsFullWindow) {
        setIsFullWindow(true);
      }
    } else {
      return;
    }
  } else {
    if (setIsFullWindow) {
      setIsFullWindow(false);
    }
  }
};

const init = () => {
  if ((screenfull as Screenfull).enabled) {
    (screenfull as Screenfull).on('change', change);
  }
};
const destroy = () => {
  if ((screenfull as Screenfull).enabled) {
    (screenfull as Screenfull).off('change', change);
  }
};
</script>
